package com.it.day5;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.FutureTask;

/**
 * ClassName: SafeDoubleCheckSingleton
 * Description: volatile实现单例模式
 *
 * @Author: csx
 * @Create: 2025/5/12 - 14:23
 * @version: v1.0
 */
public class SafeDoubleCheckSingleton {
    private static volatile SafeDoubleCheckSingleton singleton;

    private SafeDoubleCheckSingleton() {
    }

    public static SafeDoubleCheckSingleton getInstance(){
        if (singleton == null){
            synchronized (SafeDoubleCheckSingleton.class){
                if (singleton == null){
                    //隐患：多线程环境下，由于重排序，该对象可能还未完成初始化就被其他线程读取
                    singleton = new SafeDoubleCheckSingleton();
                }
            }
        }
        return singleton;
    }

    public static void main(String[] args) {
        CompletableFuture<SafeDoubleCheckSingleton> future = CompletableFuture.supplyAsync(() -> getInstance());
        CompletableFuture<SafeDoubleCheckSingleton> future1 = CompletableFuture.supplyAsync(() -> getInstance());

        SafeDoubleCheckSingleton instance = future.join();
        SafeDoubleCheckSingleton instance1 = future1.join();

        System.out.println(instance == instance1);
    }
}















